%%--------------------------------------------------------------------
%% Copyright (c) 2020 DGIOT Technologies Co., Ltd. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%%     http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(dgiot_bamis_handler).
-author("johnliu").
-behavior(dgiot_rest).
-dgiot_rest(all).
-include_lib("dgiot/include/logger.hrl").

%% API
-export([swagger_amis/0]).
-export([handle/4]).

%% API描述
%% 支持二种方式导入
%% 示例:
%% 1. Metadata为map表示的JSON,
%%    dgiot_http_server:bind(<<"/amis">>, ?MODULE, [], Metadata)
%% 2. 从模块的priv/swagger/下导入
%%    dgiot_http_server:bind(<<"/swagger_amis.json">>, ?MODULE, [], priv)
swagger_amis() ->
    [
        dgiot_http_server:bind(<<"/swagger_amis.json">>, ?MODULE, [], priv)
    ].


%%%===================================================================
%%% 请求处理
%%%  如果登录, Context 内有 <<"user">>, version
%%%===================================================================

-spec handle(OperationID :: atom(), Args :: map(), Context :: map(), Req :: dgiot_req:req()) ->
    {Status :: dgiot_req:http_status(), Body :: map()} |
    {Status :: dgiot_req:http_status(), Headers :: map(), Body :: map()} |
    {Status :: dgiot_req:http_status(), Headers :: map(), Body :: map(), Req :: dgiot_req:req()}.

handle(OperationID, Args, Context, Req) ->
    Headers = #{},
    case catch do_request(OperationID, Args, Context, Req) of
        {ErrType, Reason} when ErrType == 'EXIT'; ErrType == error ->
            Err = case is_binary(Reason) of
                      true -> Reason;
                      false -> dgiot_utils:format("~p", [Reason])
                  end,
            {500, Headers, #{<<"error">> => Err}};
        ok ->
            ?LOG(debug,"do request: ~p, ~p ->ok ~n", [OperationID, Args]),
            {200, Headers, #{}, Req};
        {ok, Res} ->
            ?LOG(debug,"do request: ~p, ~p ->~p~n", [OperationID, Args, Res]),
            {200, Headers, Res, Req};
        {Status, Res} ->
            ?LOG(debug,"do request: ~p, ~p ->~p~n", [OperationID, Args, Res]),
            {Status, Headers, Res, Req};
        {Status, NewHeaders, Res} ->
            ?LOG(debug,"do request: ~p, ~p ->~p~n", [OperationID, Args, Res]),
            {Status, maps:merge(Headers, NewHeaders), Res, Req}
    end.


%%%===================================================================
%%% 内部函数 Version:API版本
%%%===================================================================

%% iot_hub 概要: 查询平台api资源 描述:总控台
%% OperationId:get_amis
%% 请求:POST /iotapi/get_amis
do_request(get_amis, #{<<"deviceid">> := Deviceid}, _Context, _Req) ->
    case dgiot_parse:get_object(<<"Device">>, Deviceid) of
        {ok, #{<<"profile">> := Profile}} ->
            {ok, Profile};
        _ ->
            {ok, #{}}
    end;

%% iot_hub 概要: 查询amis设备
%% OperationId:get_amis
%% 请求:POST /iotapi/get_amis_device
do_request(get_amis_device, #{<<"deviceid">> := Deviceid}, _Context, _Req) ->
    case dgiot_parse:get_object(<<"Device">>, Deviceid) of
        {ok, info} ->
            {ok, info};
        _ ->
            {ok, #{}}
    end;

%% Role模版 概要: 修改amis设备
%% OperationId:put_amis_device
%% 请求:POST /iotapi/put_amis_device
do_request(put_amis_device, #{<<"objectId">> := Deviceid} = Body, #{<<"sessionToken">> := SessionToken} = _Context, _Req0) ->
   io:format("Body ~p~n", [Body]),
    case Deviceid of
        <<"Klht7ERlYn">> ->
            {ok, #{<<"code">> => 401, <<"result">> => <<"dgiot_admin Cannot be Resignation">>}};
        <<"lerYRy2jsh">> ->
            {ok, #{<<"code">> => 401, <<"result">> => <<"dgiot_admin Cannot be Resignation">>}};
        _ ->
            dgiot_bamis_handler:put_amis_device(Body, SessionToken)
    end;

%% iot_hub 概要: 删除amis设备
%% OperationId:del_amis_device
%% 请求:POST /iotapi/del_amis_device
do_request(del_amis_device, #{<<"deviceid">> := Deviceid}, _Context, _Req) ->
    case Deviceid of
        <<"Klht7ERlYn">> ->
            {ok, #{<<"code">> => 401, <<"result">> => <<"dgiot_admin Cannot be Resignation">>}};
        <<"lerY给i他gitgit'x'f'b'xRy2jsh">> ->
            {ok, #{<<"code">> => 401, <<"result">> => <<"dgiot_admin Cannot be Resignation">>}};
        _ ->
            dgiot_bamis_handler:del_amis_device(Deviceid)
    end;



%% iot_hub 概要: 创建amis设备
%% OperationId:created_amis_device
%% 请求:POST /iotapi/created_amis_device
do_request(created_amis_device, #{<<"deviceid">> := Deviceid}, #{<<"ChannelId">> := ChannelId},#{<<"DTUIP">> := DTUIP} = Body) ->
    case Deviceid of
        <<"test">> ->
            {ok, #{<<"code">> => test, <<"result">> => <<"you input test">>}};
        _ ->
        {ok, dgiot_bamis_handler:created_amis_device(Deviceid,ChannelId,DTUIP)}
    end;

%%  服务器不支持的API接口
do_request(_OperationId, _Args, _Context, _Req) ->
    ?LOG(info,"_OperationId:~p~n", [_OperationId]),
    {error, <<"Not Allowed.">>}.









